package com.cr.dataprotect.sdk;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.symmetric.SM4;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;


/**
 * 密码运算APi.（默认使用对称加密：SM4）
 *
 * @author ChenRu1
 * @Description
 * @Date 14:45 2024/4/15
 **/
@Service
public class DefaultCryptoApiImpl implements CryptoApi {
    @Override
    public String encrypt(String plaintext, String key) {
        SM4 sm4 = new SM4(HexUtil.decodeHex(key));
        return sm4.encryptHex(plaintext);
    }

    @Override
    public String decrypt(String ciphertext, String key) {
        SM4 sm4 = new SM4(HexUtil.decodeHex(key));
        return sm4.decryptStr(ciphertext);
    }

    @Override
    public String mac(String plaintext, String key) {
        // 1. 选择算法
        String algorithm = "HmacSHA256";

        // 2. 创建密钥规范
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, algorithm);

        // 3. 初始化Mac实例
        Mac mac = null;
        try {
            mac = Mac.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        try {
            mac.init(secretKeySpec);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }

        // 4. 计算HMAC
        byte[] messageBytes = plaintext.getBytes(StandardCharsets.UTF_8);
        byte[] hmacBytes = mac.doFinal(messageBytes);

        // 5. 返回Base64编码结果
        return Base64.getEncoder().encodeToString(hmacBytes);
    }


}
